<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use Cache;
use Illuminate\Support\Facades\Redis;

class UserDuration extends Command
{
    protected $signature = 'dspstack:user-duration';


    protected $description = 'Sync user duration';


    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $redis = Cache::getRedis();

        //cache的键有前缀的，见cache的配置文件
        $user_durations =  $redis->keys('*user_online_tm2-*');
        foreach ($user_durations as $item)
        {
            $user_id = explode('-', $item)[1];
            $tm2 = Cache::get('user_online_tm2-'.$user_id);
            $tm1 = Cache::get('user_online_tm1-'.$user_id);
            if($tm1 && $tm2)
            {
                $duration = $tm2 - $tm1;
                User::where('id',$user_id)->increment('online_duration',$duration);
                Cache::forget('user_online_tm1-'.$user_id);
                Cache::forget('user_online_tm2-'.$user_id);
            }

        }
//        $redis = Redis::connection('default');
//        //获取所有用户的在登录数据
//        $user_durations =  $redis->keys('local:duration:*');
//        foreach ($user_durations as $item) {
//            //从key中截取用户id
//            $user_id=ltrim(strstr($item,'_'),'_');
//
//            //获取登录时间与登出时间，获取时间长度
//            $logout_time=$redis->lindex($item, 1);
//            $login_time=$redis->lindex($item, 0);
//            $duration=floor(strtotime($logout_time)-strtotime($login_time));
//            User::where('id',$user_id)->increment('online_duration',$duration);
//            $redis->del($item);
//        }

        $this->info('Done!');
    }
}
